import {useFocusEffect} from '@react-navigation/native';
import {Empty, Header, ObserverText, ObserverView} from '../../../components';
import {useCallback} from 'react';
import {AccountChangeRecords} from '../../../services';
import {useUserInfoStore} from '../../../mobx';
import {observer} from 'mobx-react-lite';
import {useTableReducer} from '../../../hooks';
import {FlatList, View} from 'react-native';
import {dpw16, dpw20, dpw4} from '../../../constants';
import {getMD, getYM} from '../../../utils';

const PayHistory = observer(({navigation}: any) => {
  const {userInfo} = useUserInfoStore();
  const [{data, total, pageIndex}, dispatch] = useTableReducer();

  const getPayHistory = useCallback(
    (idx: number = 1, isMore?: boolean) => {
      if (userInfo?.Token) {
        AccountChangeRecords({
          UT: userInfo?.Token,
          EndTime: '',
          PageIndex: idx,
          PageSize: 10,
          StartTime: '',
        })
          .then((res: any) => {
            dispatch({
              type: 'success',
              payload: {
                data: isMore
                  ? (preD: any[]) => [...preD, ...res.Data]
                  : res?.Data,
                total: res.Count,
                pageIndex: idx,
              },
            });
          })
          .catch(() => {});
      }
    },
    [userInfo?.Token],
  );

  useFocusEffect(getPayHistory);

  const _renderItem = ({item}: any) => {
    return (
      <ObserverView
        style={{
          paddingHorizontal: dpw16,
          paddingVertical: dpw20,
          borderBottomWidth: 1,
        }}
        themeStyle={{borderColor: 'color_9'}}>
        <View style={{flexDirection: 'row'}}>
          <ObserverView
            style={{
              borderRightWidth: 1,
              paddingRight: dpw20,
              marginRight: dpw20,
              alignItem: 'center',
              justifyContent: 'center',
            }}
            themeStyle={{borderColor: 'color_9'}}>
            <ObserverText tKey={getMD(item.InsertTime)} type="desc" />
          </ObserverView>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              flex: 1,
              overflow: 'hidden',
            }}>
            <View style={{flex: 1}}>
              <ObserverText tKey={item.Title} size="normal" />
              <ObserverText
                style={{marginTop: dpw4}}
                tKey={item.Content}
                numberOfLines={1}
                ellipsizeMode="tail"
                type="desc"
              />
            </View>
            <ObserverText
              tKey="bookCurrency"
              tOptions={{value: item.ChangeNumber}}
              themeStyle={{
                color: item.ChangeNumber >= 0 ? 'color_46' : 'color_11',
              }}
            />
          </View>
        </View>
      </ObserverView>
    );
  };

  const onLoadMore = () => {
    if (
      typeof total === 'number' &&
      Array.isArray(data) &&
      total > data.length
    ) {
      getPayHistory(pageIndex + 1, true);
    }
  };

  return (
    <ObserverView style={{flex: 1}} themeStyle={{backgroundColor: 'color_12'}}>
      <Header title="purchaseHistory" navigation={navigation} isCenter />
      {Array.isArray(data) && data.length > 0 ? (
        <View>
          <ObserverText
            tKey={getYM(data[0]?.InsertTime)}
            style={{paddingVertical: dpw4, paddingLeft: dpw16}}
            size="small"
            colorType="text-3"
          />
          <FlatList
            data={data}
            renderItem={_renderItem}
            keyExtractor={it => `${it.Content + it.InsertTime}`}
            onEndReached={onLoadMore}
          />
        </View>
      ) : (
        <Empty />
      )}
    </ObserverView>
  );
});

export default PayHistory;
